<template>
  <div>
    <el-row>
      <el-col :xs="0" :lg="2"></el-col>
      <el-col :xs="18" :lg="14" style="padding: 15px">
        <el-card style="background-color: #efeeec">
          <el-container>
            <el-aside width="328px">
              <el-image
                style="width: 328px; height: 440px"
                :src="detail.image"
              ></el-image>
            </el-aside>
            <el-container>
              <el-header class="detail-header">
                <el-text class="detail-title">{{ detail.Dish_name }}</el-text>
                <div style="padding-top: 15px">
                  <el-text
                    >{{ detail.fav_num }} 收藏 ·
                    {{ detail.view_num }} 浏览</el-text
                  >
                </div>
              </el-header>
              <el-main class="detail-main">
                <div class="main-top">
                  <div class="detail-description" v-for="item in svg">
                    <div class="top">
                      <img :src="item.svg" />
                    </div>
                    <div class="bottom">
                      <p
                        style="
                          font-size: 12px;
                          padding-bottom: 15px;
                          color: #f5b000;
                        "
                      >
                        {{ item.title }}
                      </p>
                      <p style="font-size: 16px; font-weight: bold">
                        {{ item.value }}
                      </p>
                    </div>
                  </div>
                </div>

                <div class="detail-ingredients">
                  <div class="left">
                    <span
                      style="font-size: large; font-weight: 550; margin: auto"
                      >用料：</span
                    >
                  </div>
                  <div class="right">
                    <el-tag
                      v-for="item in ingredients"
                      effect="plain"
                      style="height: 30px; font-size: 16px; font-family: '楷体'"
                      >{{ item }}</el-tag
                    >
                  </div>
                </div>
                <div class="detail-ingredients">
                  <div class="left">
                    <span
                      style="font-size: large; font-weight: 550; margin: auto"
                      >功效：</span
                    >
                  </div>
                  <div class="right">
                    <el-tag
                      v-for="item in category"
                      effect="plain"
                      round
                      style="height: 30px; font-size: 15px; font-family: '楷体'"
                      >{{ item }}</el-tag
                    >
                  </div>
                </div></el-main
              >
              <el-footer class="detail-footer">
                <el-button
                  type="danger"
                  round
                  :icon="Star"
                  size="large"
                  @click="addFavorite"
                  >收藏</el-button
                >
              </el-footer>
            </el-container>
          </el-container>
        </el-card>

        <el-card class="box-card" style="margin-top: 20px">
          <template #header>
            <div class="card-header">
              <span>制作步骤</span>
              <el-button style="margin-top: 12px" @click="next"
                >下一步</el-button
              >
            </div>
          </template>
          <el-steps align-center :active="active" finish-status="success">
            <el-step
              v-for="(item, index) in steps"
              :title="`步骤${index + 1}`"
              :description="item.replace(/^\d+/, '')"
            />
          </el-steps>
        </el-card>
      </el-col>
      <el-col :xs="6" :lg="6" style="padding: 15px">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>猜你喜欢</span>
            </div>
          </template>
          <div
            v-for="(item, index) in similar"
            class="similar"
            @click="toDetail(item.id)"
          >
            <div
              style="
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
              "
            >
              <el-image
                style="width: 150px; height: 150px"
                :src="item.image"
                fit="fill"
              />
              <span class="demonstration">{{ item.name }}</span>
            </div>
          </div>
        </el-card>
        <el-card>
          <template #header>
            <div class="card-header">
              <span>菜谱营养分析（根据所含全部食材计算）</span>
            </div>
          </template>
          <div class="charts" ref="charts"></div>
        </el-card>
      </el-col>
      <el-col :xs="0" :lg="2"></el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRoute } from "vue-router";
import { reqDetail, reqSimilar, reqAddView } from "../../api/menu";
import { reqAddFavorite } from "../../api/user";
import taste from "@/assets/svg/taste.svg";
import time from "@/assets/svg/time.svg";
import method from "@/assets/svg/method.svg";
import { Star } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import * as echarts from "echarts";
import { ElMessage } from "element-plus";
let router = useRouter();
let charts = ref();
const route = useRoute();
const active = ref(0);
const id = ref(route.query.id);
const ingredients = ref([]);
const steps = ref([]);
const category = ref([]);
const svg = ref([
  {
    svg: taste,
    title: "口味",
    value: "",
  },
  {
    svg: time,
    title: "时间",
    value: "",
  },
  {
    svg: method,
    title: "工艺",
    value: "",
  },
]);
const detail = ref({
  Dish_name: "",
  image: "",
  category: "",
  Ingredients: "",
  fav_num: 0,
  view_num: 0,
  meal_type: "",
  Ingredients: "",
  Main_Technique: "",
  Method: "",
  Taste: "",
  Cooking_Time: "",
  User_List: "",
});
const title = ref("");
const similar = ref([]);
const jztData = ref([
  {
    value: 20,
    content: 0,
    unit: "克",
    name: "糖",
    title: "糖尿病人群",
    type: "",
    color: "",
  },
  {
    value: 60,
    content: 0,
    name: "脂肪",
    unit: "克",
    title: "高血脂人群",
    type: "",
    color: "",
  },
  {
    value: 40,
    name: "能量",
    content: 0,
    unit: "大卡",
    title: "减肥人群",
    type: "",
    color: "",
  },
]);
const next = () => {
  if (active.value++ > steps.value.length - 1) active.value = 0;
};
const getdetail = async () => {
  let res = await reqDetail(id.value);
  detail.value = res.data;
  console.log(detail.value);
  try {
    ingredients.value = eval("(" + detail.value.Ingredients + ")");
    steps.value = eval("(" + detail.value.Method + ")");
    category.value = eval("(" + detail.value.category + ")");
    console.log(ingredients);
  } catch (err) {
    console.error("解析JSON出错:", err);
  }
  svg.value[0].value = detail.value.Taste;
  svg.value[1].value = detail.value.Cooking_Time;
  svg.value[2].value = detail.value.Main_Technique;
  jztData.value[0].content = res.data.Calories;
  jztData.value[1].content = res.data.Carbohydrates_y;
  jztData.value[2].content = res.data.Fat_y;
  filterJDT(jztData.value);
  console.log(jztData);
};
const getSimilar = async () => {
  const data = {
    dish_name: detail.value.Dish_name,
    taste: detail.value.Taste,
    method: detail.value.Main_Technique,
    id: detail.value.id,
  };
  let res = await reqSimilar(data);
  similar.value = res.data;
  console.log(similar);
};
onMounted(async () => {
  await addView();
  await getdetail();
  await getSimilar();
  await initEchart();
});
const addView = async () => {
  let res = await reqAddView(id.value);
};
const toDetail = (value) => {
  router.push({
    path: "/detail",
    query: {
      id: value,
    },
  });
  id.value = value;
  getdetail();
};
const filterJDT = () => {
  const colors = ["#f2675b", "#ffc835", "#1ccd8e"];
  if (jztData.value[0].content > 0 && jztData.value[0].content < 5) {
    jztData.value[0].type = 0;
    jztData.value[0].color = colors[2];
  } else if (jztData.value[0].content >= 5 && jztData.value[0].content < 10) {
    jztData.value[0].type = 1;
    jztData.value[0].color = colors[1];
  } else if (jztData.value[0].content >= 10) {
    jztData.value[0].type = 2;
    jztData.value[0].color = colors[0];
  }
  if (jztData.value[1].content > 0 && jztData.value[1].content < 5) {
    jztData.value[1].type = 0;
    jztData.value[1].color = colors[2];
  } else if (jztData.value[1].content >= 5 && jztData.value[1].content < 20) {
    jztData.value[1].type = 1;
    jztData.value[1].color = colors[1];
  } else if (jztData.value[1].content >= 20) {
    jztData.value[1].type = 2;
    jztData.value[1].color = colors[0];
  }
  if (jztData.value[2].content > 0 && jztData.value[2].content < 150) {
    jztData.value[2].type = 0;
    jztData.value[2].color = colors[2];
  } else if (
    jztData.value[2].content >= 150 &&
    jztData.value[2].content < 300
  ) {
    jztData.value[2].type = 1;
    jztData.value[2].color = colors[1];
  } else if (jztData.value[2].content >= 300) {
    jztData.value[2].type = 2;
    jztData.value[2].color = colors[0];
  }
};
const initEchart = () => {
  jztData.value.forEach((item) => {
    if (item.type <= 1) title.value += item.title + " ";
  });
  let mycharts = echarts.init(charts.value);
  let option = {
    backgroundColor: "#fff",
    title: {
      text: "营养分析", // 设置底部标题文本
      subtext: `本菜谱适合人群：${title.value}`,
      left: "center", // 标题居中显示
      bottom: 5, // 距离底部的距离，根据需要调整
      textStyle: {
        // 标题样式配置
        fontSize: 16,
        color: "#333",
      },
    },
    tooltip: {
      trigger: "item",
      formatter: function (params) {
        switch (params.data.type) {
          case 0:
            return params.data.title + "\n" + "多吃";
          case 1:
            return params.data.title + "\n" + "少吃";
          case 2:
            return params.data.title + "\n" + "不吃";
        }
      },
    },
    legend: {
      //图例
      left: "5%", //图例组件离容器左侧的距离：靠左
      orient: "vertical", //图例列表的布局朝向：垂直
      data: jztData.value,
    },
    series: [
      {
        zlevel: 1,
        name: "漏斗图",
        type: "funnel",
        left: "0%",
        width: "100%",
        min: 0,
        top: 0,
        max: 120,
        minSize: "0%",
        maxSize: "180%",
        sort: "ascending",
        gap: 5,
        label: {
          show: true,
          position: "inside",
          width: "200px",
          align: "right",
          color: "#fff",
          fontSize: 16,
          formatter: function (params) {
            return (
              params.data.name + "\n" + params.data.content + params.data.unit
            );
          },
        },
        itemStyle: {
          borderColor: "#fff",
          borderWidth: 1,
        },
        emphasis: {
          label: {
            fontSize: 20,
          },
        },
        data: jztData.value.map((item) => ({
          ...item, // 包含原始数据的所有属性
          itemStyle: {
            // 添加或覆盖item样式以应用颜色
            color: item.color,
          },
        })),
      },
    ],
  };
  mycharts.setOption(option);
  console.log(1111);
};
const addFavorite = async () => {
  const data = {
    userid: localStorage.getItem("id"),
    meal_id: id.value,
  };
  let res = await reqAddFavorite(data);
  console.log(res);
  ElMessage.success(res.msg);
  await getdetail();
};
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.detail-main {
  display: flex;
  flex-direction: column;
  .main-top {
    width: 50%;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
  }
}
.detail-ingredients {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  border-radius: 25px;
  overflow: hidden;
  margin-top: 10px;
  .left {
    width: 70px;
    height: 80px;
    display: flex;
    text-align: center;
    background-color: #ffe851;
  }
  .right {
    display: flex;
    height: 80px;
    width: 600px;
    align-items: center;
    gap: 5px;
    flex-wrap: wrap;
    background-color: #fff;
  }
}
.detail-title {
  color: black;
  font-size: 25px;
  font-weight: bolder;
}
.detail-description {
  width: 80px;
  height: 150px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  border-radius: 15px;
  position: relative;
  overflow: hidden;
  background-color: #fff;
  .top {
    height: 70%;
    position: relative;
    border-radius: 0 0 0 88px;
    background-color: #f7f7f7;
    & > img {
      position: absolute;
      top: -10px;
      right: -15px;
      z-index: 2;
      height: 70px;
      width: 70px;
    }
  }
  .bottom {
    bottom: 20px;
    position: absolute;
  }
}
.detail-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.similar {
  padding: 10px;
  display: inline-block;
  width: 50%;
  box-sizing: border-box;
  align-items: center;
  flex-wrap: wrap;
  vertical-align: top;
}
.demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 16px;
  text-align: center;
  justify-content: center;
  margin-top: 10px;
}
.similar:hover {
  cursor: pointer;
  .demonstration {
    color: #f75145;
    text-decoration: underline;
  }
}
.charts {
  width: 100%;
  height: 400px;
}
</style>
